package club.beimeng.demos.demo2021年5月18日;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class One {

    static int map[][] = null;
    static int n = 0;
    static int m = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {

            n = sc.nextInt();
            m = sc.nextInt();
            map = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    map[i][j] = sc.nextInt();
                }
            }

            fbs(n, m);

        }
    }


    private static void fbs(int n, int m) {
        int[][] d = new int[n][m];//记录走过的点，把0变为1
        Queue<Node> q = new LinkedList<Node>();
        int fx[][] = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};//方向四个都懂

        q.offer(new Node(0, 0));//加入起点0，0

        //queue.poll(); 返回第一个元素，并在队列中删除
        while (!q.isEmpty()) {
            Node node = q.poll();
            if (node.x == n - 1 && node.y == m - 1) {//判断是否到终点
                break;
            }
            for (int i = 0; i < 4; i++) { //四个方向都要判断一下
                int x = node.x + fx[i][0];
                int y = node.y + fx[i][1];
                if (x >= 0 && y >= 0 && x < n && y < m && map[x][y] == 0 && d[x][y] == 0) {//判断边界，是否可走。
                    q.add(new Node(x, y));
                    d[x][y] = d[node.x][node.y] + 1;//由0变为1
                }
            }
        }
        System.out.println(d[n - 1][m - 1]);
    }
}

class Node {
    int x;
    int y;

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
    }
}




/*
 *
 * @author Mr.Bao
 * @date
 */